﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using ExtensibleEventViewer.Console.Forms;


namespace ExtensibleEventViewer.Console.Controls
{
	public partial class ComputerListControl : UserControl
	{
		public ComputerListControl()
		{
			InitializeComponent();
		}

		private void PopulateComputerListBox(IEnumerable<string> computerList)
		{
			if (computerList != null)
			{
				clbComputerList.BeginUpdate();

				clbComputerList.Items.Clear();

				foreach (string computerName in computerList)
				{
					clbComputerList.Items.Add(computerName);
				}

				clbComputerList.EndUpdate();
			}
		}

		public IEnumerable<string> SelectedComputerNames
		{
			get
			{
				foreach (object selectedItem in clbComputerList.SelectedItems)
				{
					yield return (string) selectedItem;
				}
			}
		}

		public IEnumerable<string> ComputerNames
		{
			get
			{
				foreach (object selectedItem in clbComputerList.Items)
				{
					yield return (string)selectedItem;
				}
			}
			set
			{
				if (clbComputerList.InvokeRequired)
				{
					Action populateList = () => PopulateComputerListBox(value);

					clbComputerList.Invoke(populateList);
				}
				else
				{
					PopulateComputerListBox(value);
				}
			}
		}

		public void AddComputer(string computerName)
		{
			bool isComputerNameInList = false;

			foreach (string item in clbComputerList.Items)
			{
				if (string.Equals(item, computerName))
				{
					isComputerNameInList = true;
					break;
				}
			}

			if(!isComputerNameInList)
			{
				clbComputerList.BeginUpdate();
				clbComputerList.Items.Add(computerName);
				clbComputerList.EndUpdate();
			}
		}

		public void DeleteSelectedComputernames()
		{
			clbComputerList.BeginUpdate();

			while (clbComputerList.CheckedIndices.Count > 0)
			{
				clbComputerList.Items.RemoveAt(clbComputerList.CheckedIndices[0]);
			}

			clbComputerList.EndUpdate();
		}

		private void OnAddComputerClick(object sender, EventArgs e)
		{
			using (AddComputerWnd addComputerWnd = new AddComputerWnd())
			{
				addComputerWnd.AddComputer += AddComputer;

				addComputerWnd.ShowDialog(this);
			}
		}
	}
}
